﻿using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.Authorization;
using IM.Easy.AuthorizationServices.Dtos;
using IM.Easy.AuthorizationServices.IServices;
using System.Net;
using System.Security.Cryptography;

namespace IM.Easy.AuthorizationServices.Services
{
    public class RefreshTokenService : AppServices<RefreshToken>, IRefreshTokenService
    {

        public RefreshTokenService(ISqlSugarClient db) : base(db)
        {

        }

        public RefreshToken Create(RefreshToken entity)
        {
            // TODO: 添加创建逻辑
            return Context.Insertable(entity).ExecuteReturnEntity();
        }

        public RefreshToken GetById(long id)
        {
            // TODO: 添加获取逻辑
            return Context.Queryable<RefreshToken>().InSingle(id);
        }

        public PageResponse<RefreshToken> GetPageList(RefreshTokenQueryDto query)
        {
            var queryable = Context.Queryable<RefreshToken>();
            var exp = Expressionable.Create<RefreshToken>();
            exp = exp
;
            var page = queryable
                 .Where(exp.ToExpression())
                 .ToPageList<RefreshToken, RefreshToken>(query);
            return page;
        }

        public bool Update(RefreshToken entity)
        {
            // TODO: 添加更新逻辑
            return Context.Updateable(entity).ExecuteCommandHasChange();
        }

        public bool Delete(params long[] Id)
        {
            // TODO: 添加删除逻辑
            return Context.Deleteable<RefreshToken>(Id).ExecuteCommandHasChange();
        }


        /// <summary>
        /// 生成刷新token
        /// </summary>
        /// <returns></returns>
        public RefreshToken Generate()
        {
            return new RefreshToken
            {
                Token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
                                .Replace('+', '-')
                                .Replace('/', '_')
                                .TrimEnd('='),
                Expires = DateTime.Now.AddDays(7),
            };
        }

        /// <summary>
        /// 验证刷新token有效性
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public bool ValidateToken(string token)
        {
            // 1. 检查令牌是否为空
            if (string.IsNullOrWhiteSpace(token))
                return false;

            // 2. 查询令牌是否存在
            var instance = GetFirst(s => s.Token == token);

            if (instance == null)
                return false;

            if (!instance.IsActive)
                return false;

            // 3. 检查关联用户状态 
            if (instance.User != null && !instance.User.IsActive)
                return false;

            return true;

        }

        /// <summary>
        /// 吊销刷新令牌
        /// </summary>
        public void Revoke(string token, string? replacedByToken = null)
        {
            var refreshToken = GetFirst(s => s.Token == token);

            if (refreshToken != null && !refreshToken.IsRevoked)
            {
                refreshToken.Revoked = DateTime.Now;
                refreshToken.ReplacedByToken = replacedByToken;
                Update(refreshToken);
            }
        }

        /// <summary>
        /// 通过刷新token获取token相关信息
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public long GetUserId(string token)
        {
            var userId = Context.Queryable<RefreshToken>()
                  .Where(s => s.Token == token)
                  .Select(s => s.UserId)
                  .First();
            return userId;
        }
    }
}
